package com.doudizu.shoesonline.controller;

import cn.hutool.core.lang.UUID;
import com.doudizu.shoesonline.model.entity.Link;
import com.doudizu.shoesonline.service.LinkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ln
 */
@RestController
@RequestMapping("/file")
@Api(tags = "文件")
public class FileController {

    @Resource
    private LinkService linkService;

    @Value("${file.path.picture:}")
    String pictureFolder;

    @Value("${file.path.prefix:}")
    String fileUrl;


    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public List<Integer> getPicLinkIds(List<MultipartFile> files) {

        List<Integer> ids = files.stream().map(multipartFile -> {
            String fileName = UUID.randomUUID() + "-" + multipartFile.getOriginalFilename();
            File folder = new File(pictureFolder);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            String path = pictureFolder + fileName;
            File file = new File(path);
            Link link = new Link();
            link.setLinkName(fileName);
            link.setType(2);
            link.setUrl(fileUrl+fileName);
            linkService.saveOrUpdate(link);
            try {
                multipartFile.transferTo(file);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return link.getId();
        }).collect(Collectors.toList());

        return ids;
    }
}
